// miniprogram/pages/appointment/index.js
const { formatTime } = require('../../utils/util.js');
const { timeDifference } = require('../../utils/timeDifference.js');
const deviceId = getApp().globalData.deviceId;
const API_KEY = getApp().globalData.API_KEY;

Page({

  /**
   * 页面的初始数据
   */
  data: {
    marker:{},
    openId:'',
    show:false,
    orderTime:formatTime(new Date()),
    minHour:(new Date()).getHours(),
    maxHour:23,
    userData:wx.getStorageSync('userData'),
    orderHours:'',
    orderId:'',
    state:null
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getLastPageData();
    this.getDevicePower(deviceId);
    this.setData({ openId:wx.getStorageSync('userInfo').openId });
  },

  getLastPageData(){
    const that = this;
    const eventChannel = this.getOpenerEventChannel();
    eventChannel.on('getMarker', function(res) {
      that.setData({  
        marker:res.data
      })
    })
  },

  chooseTime(){
    this.setData({ show:true })
  },

  onClose() {
    this.setData({ show: false });
  },
  
  onConfirm(e){
    this.setData({
      show:false,
      orderTime:e.detail
    })
  },

  onCancel(){
    this.onClose();
  },

  inputOrderHours(e){
    this.setData({
      orderHours:e.detail
    })
  },

  getDevicePower(_deviceId){
    let datastreams_id = 'zhuangtai';
    const that = this;
    wx.request({
      url: `https://api.heclouds.com/devices/${_deviceId}/datastreams/${datastreams_id}`,
      header: {
        "api-key":API_KEY
      },
      method: "GET",
      success: (result) => {     
        that.setData({ state:result.data.data.current_value });
      },
      fail: (res) => {
        console.error(res);
      }
    })
  },
  
  submit(){
    const openId = this.data.openId;
    const orderHours = this.data.orderHours;
    const markerId = this.data.marker.id;
    const deviceId = (this.data.marker.deviceId).toString();
    const orderTime = this.data.orderTime;
    // const price = this.data.price;
    if ((orderHours.trim() === '') || orderHours > 1000 || orderHours <= 0 || Math.round(orderHours) != orderHours) {
      wx.showToast({
        title: '请输入1~1000的整数',
        icon:'none'
      })
      return;
    }else{
      const that = this;
      wx.showLoading({
        title: '提交申请中',
        success:()=>{
          that.onQuery(openId,markerId,deviceId,'will',orderHours,orderTime);
        }
      })
    }
  },

  onAdd: function (openId,markerId,deviceId,orderType,orderHours,orderTime) {
    const db = wx.cloud.database()
    db.collection('orders').add({
      data: {
        markerId:markerId,
        deviceId:deviceId,
        orderType:orderType,
        timestemp:(new Date()).valueOf(),
        orderHours:orderHours,
        orderTime:orderTime, 
        endTimestemp:null,
        timeLeft:orderHours
      },
      success: res => {
        // 在返回结果中会包含新创建的记录的 _id
        this.setData({
          orderId: res._id,
        })
        wx.hideLoading();
        wx.showToast({
          title: '预约成功',
            mask:true,
            success(){
              wx.switchTab({
                url: '/pages/index/index'
              })
            }
        })
        console.log('[数据库] [新增记录] 成功，记录 _id: ', res._id)
      },
      fail: err => {
        wx.hideLoading({
          success: (res) => {
            wx.showToast({
              icon: 'none',
              title: '预约失败'
            })
          },
        })
        console.error('[数据库] [新增记录] 失败：', err)
      }
    })
  },

  onQuery: function(openId,markerId,deviceId,orderType,orderHours,orderTime) {  
    const that = this;
    wx.cloud.callFunction({
      name:'queryOrder',
      data:{
        orderType:orderType,
        deviceId:deviceId
      }
    }).then((res)=>{
      wx.hideLoading();
      let orders = [];
      orders = res.result.data;
      console.log(orders);
      const hasOrder = orders.some(v=>{
        return timeDifference(v.orderTime,orderTime,v.orderHours,orderHours)<0
      })
      if (hasOrder === true) {
        wx.showToast({
          title: '该时段不可预约',
          icon:'error'
        })
      }else if (hasOrder === false) {
        wx.cloud.callFunction({
          name:'queryOrder',
          data:{
            orderType:'going',
            deviceId:deviceId
          }
        }).then((re)=>{
          let nowOrders = re.result.data || [];
          console.log('nowOrders',nowOrders);
          if (nowOrders.length === 0) {
            that.onAdd(openId,markerId,deviceId,orderType,orderHours,orderTime); 
          }else if (nowOrders.length > 0) {
            const leftime = nowOrders.some(element =>{
              return ((new Date()).valueOf()) <= (element.timestemp + (parseInt(orderHours))*60*1000)
            });
            if (leftime === true) {
              wx.showToast({
                title: '该时段不可预约',
                icon:'error'
              })
            }else if( leftime === false ){
              that.onAdd(openId,markerId,deviceId,orderType,orderHours,orderTime); 
            }
          }   
        })  
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    
  }
})